import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import EditTemplate from '@/components/EditTemplate';
import CapitalSource from '@/pages/components/capitalSource';
import { Table, Card, Row, Button, Modal, Input, message } from 'antd';
import TableList from '@/components/TableList';
import { timeFormat } from '@/utils/common';
import Status from '@/pages/components/Status';
import { getStatus } from '@/utils/business';

import styles from './index.less';
import AuthButton from '@/components/AuthButton';
const { TextArea } = Input;
const BuildEdit = ({ location, dispatch, dict, url }: any) => {
  const [detail, setDetail] = useState({ buildType: 'BUILD' });
  const [onlyRead, setonlyRead] = useState(false);
  const [approveList, setapproveList] = useState([]);
  const [showModal, setshowModal] = useState(false);
  const [comment, setcomment] = useState('');
  const {
    id,
    transType,
    fromType = 3,
    readOnly,
    isApprove = false,
  } = location.query;
  const transUrl = {
    1: '/api/project/report/v1/annualToPlan',
    5: '/api/project/report/v1/storeToPlan',
  };
  const updateUrl = '/api/project/report/v1/planReport/update';
  const createUrl = '/api/project/report/v1/planReport/create';
  const saveUrl = transType ? transUrl[fromType] : id ? updateUrl : createUrl;
  const pointType = { 3: 'PLAN', 1: 'ANNUAL', 9: 'MONEY' }[fromType];
  useEffect(() => {
    if (id) {
      const urlObj: any = {
        1: '/api/project/report/v1/annualReport/detail',
        3: '/api/project/report/v1/planReport/detail',
        5: '/api/project/report/v1/storeReport/detail',
      };
      setonlyRead(readOnly);
      dispatch({
        type: '$request/post',
        payload: {
          url: url || urlObj[fromType],
          data: {
            uuid: id,
            page: 0,
            size: 10,
          },
        },
      }).then(res => {
        console.log('储备项目申报详情：', res);
        if (res) {
          getApproveList(res.uuid);
          setDetail({
            ...res,
            professionDataUuid: res.professionData.uuid,
            serviceTypeDataUuid: res.serviceTypeData.uuid,
            projectUuid: res.project.uuid,
            createTime: timeFormat(res.createTime),
            buildType: 'BUILD',
          });
        } else {
          setDetail({});
        }
      });
    }
  }, []);

  const getApproveList = id => {
    //---------------- 获取审批节点 ---------
    readOnly &&
      dispatch({
        type: '$request/post',
        payload: {
          url: '/api/project/approve/v1/result/list',
          data: { uuid: id, pointType },
        },
      }).then(res => {
        const list = res.map(item => {
          return {
            ...item,
            createTime: timeFormat(item.createTime),
            name: item.department.name + '审批',
          };
        });
        setapproveList(list);
      });
  };

  const setTotal = data => {
    console.log(data.total);
    setDetail({
      ...detail,
      fundSource: data,
      totalInvestment: data.total,
    });
    // totalInvestment
  };

  const filters = [
    {
      title: '项目信息',
      list: [
        {
          key: 'name',
          type: 'input',
          label: '项目名称',
          span: 12,
          placeholder: '请输入项目名称',
        },
        {
          key: ['project', 'no'],
          type: 'text',
          label: '项目ID',
          span: 12,
        },
        {
          key: 'ownerOrgUnit',
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'professionDataUuid',
          type: 'select',
          label: '行业领域',
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'profession',
            },
          },
          span: 12,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'buildType', //TODO: 这里未补充
          type: 'select',
          label: '项目性质',
          span: 12,
          disabled: true,
          options: [
            {
              label: '建设',
              value: 'BUILD',
            },
            {
              label: '保障',
              value: 'PURCHASE_SERVICE',
            },
          ],
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'serviceTypeDataUuid',
          type: 'select',
          label: '项目类型',
          span: 12,
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'service',
            },
          },
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'description',
          type: 'textarea',
          label: ' 项目简介',
          span: 24,
          rules: [{ required: true }],
        },
        {
          key: 'fundSource',
          type: 'custom',
          label: ' 资金来源',
          span: 24,
          rules: [{ required: true }],
          render: (
            <CapitalSource
              readOnly={readOnly}
              onChange={e => setTotal(e)}
              detail={detail}
            />
          ),
        },
        {
          key: 'totalInvestment',
          type: 'input',
          label: '总投资',
          span: 24,
          disabled: true,
          placeholder: '请选择',
          prop: {
            addonAfter: '万元',
          },
          rules: [
            {
              required: true,
              pattern: new RegExp(/^-?\d+/, 'g'),
              message: '只能输入数字',
            },
          ],
        },
        {
          key: 'expectStartYear',
          type: 'select',
          label: ' 拟开建年份',
          span: 12,
          options: dict.fiveYears,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'expectCompleteYear',
          type: 'select',
          label: ' 拟建成年份',
          span: 12,
          options: dict.fiveYears,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'contactPersonName',
          type: 'input',
          label: ' 联系人',
          span: 12,
          rules: [{ required: true }],
        },
        {
          key: 'contactPersonPhone',
          type: 'input',
          label: ' 联系人电话',
          span: 12,
          rules: [{ required: true }],
        },
        {
          key: 'liablePersonName',
          type: 'input',
          label: '负责人',
          span: 12,
          placeholder: '请输入负责人',
          rules: [{ required: true }],
        },
        {
          key: 'liablePersonPhone',
          type: 'input',
          label: '负责人电话',
          span: 12,
          placeholder: '请输入负责人电话',
          rules: [{ required: true }],
        },
        {
          key: 'remark',
          type: 'textarea',
          label: ' 备注',
          span: 24,
        },
        {
          key: 'createTime',
          type: 'text',
          label: '申报日期',
          span: 24,
          hidden: !readOnly,
        },
      ],
    },
  ];
  const columns = [
    { title: '审批节点', dataIndex: 'name', width: 150 },
    {
      title: '审批时间',
      dataIndex: 'createTime',
      width: 250,
      render: (text, data) => (getStatus(data, 3) ? text : ''),
    },
    {
      title: '审批结果',
      dataIndex: 'result',
      width: 150,
      render: (text, data) => <Status data={data} type={3} />,
    },
    { title: '审批意见', dataIndex: 'comment' },
  ];
  const handleResult = type => {
    if (!comment && !type) {
      message.error('拒绝时请输入审批意见');
      return;
    }
    if (!detail || !detail.approveResult) {
      return message.error('项目信息不正确');
    }
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/project/approve/v1/approve',
        data: {
          projectType: 'PLAN',
          comment: comment,
          result: type,
          uuid: detail.approveResult.uuid,
        },
      },
    }).then(() => {
      message.success('审批成功');
      dispatch({ type: '$router/back' });
    });
  };
  return (
    <div>
      <EditTemplate
        filters={filters}
        initialValues={detail}
        updateUrl={saveUrl}
        isDetail={onlyRead}
        readOnly={onlyRead}
        footer={
          isApprove && (
            <Button type="primary" onClick={() => setshowModal(true)}>
              审批
            </Button>
          )
        }
      />
      {readOnly && (
        <Card title="审批信息">
          <Table
            bordered
            tableLayout="fixed"
            dataSource={approveList}
            columns={columns}
          ></Table>
        </Card>
      )}

      <Modal
        title="审批意见"
        visible={showModal}
        okText="通过"
        cancelText="拒绝"
        onCancel={() => setshowModal(false)}
        footer={[
          <AuthButton
            key="back"
            onClick={() => handleResult(false)}
            role="examine_plan_project"
          >
            拒绝
          </AuthButton>,
          <AuthButton
            type="primary"
            onClick={() => handleResult(true)}
            role="examine_plan_project"
          >
            通过
          </AuthButton>,
        ]}
      >
        <TextArea
          placeholder="审批意见，拒绝时必填"
          value={comment}
          onChange={e => setcomment(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default connect((state: any) => state.base)(BuildEdit);
